# 使用训练好的XGBoost模型进行预测
import pandas as pd
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_score, roc_auc_score, recall_score,f1_score
from train_xgboost import train_xgboost, evaluate_model
from shared_functions import read_from_files
import time
start_time = time.time()
print("### 开始计时 ###")
# 加载数据
print("### Load files ###")
DIR_INPUT = 'simulated-data-transformed/' 

BEGIN_DATE = "2025-06-11"
END_DATE = "2025-09-14"

transactions_df = read_from_files(DIR_INPUT, BEGIN_DATE, END_DATE)

# 输出特征
output_feature = "TX_FRAUD"
# 输入特征
input_features = ['TX_AMOUNT','TX_DURING_WEEKEND', 'TX_DURING_NIGHT', 'CUSTOMER_ID_NB_TX_1DAY_WINDOW',
       'CUSTOMER_ID_AVG_AMOUNT_1DAY_WINDOW', 'CUSTOMER_ID_NB_TX_7DAY_WINDOW',
       'CUSTOMER_ID_AVG_AMOUNT_7DAY_WINDOW', 'CUSTOMER_ID_NB_TX_30DAY_WINDOW',
       'CUSTOMER_ID_AVG_AMOUNT_30DAY_WINDOW', 'TERMINAL_ID_NB_TX_1DAY_WINDOW',
       'TERMINAL_ID_RISK_1DAY_WINDOW', 'TERMINAL_ID_NB_TX_7DAY_WINDOW',
       'TERMINAL_ID_RISK_7DAY_WINDOW', 'TERMINAL_ID_NB_TX_30DAY_WINDOW',
       'TERMINAL_ID_RISK_30DAY_WINDOW']


# 加载已经训练好的模型
print("### Load trained XGBoost model ###")
model = xgb.XGBClassifier()
model.load_model('xgboost_fraud_detection.model')
# 准备测试数据
X = transactions_df[input_features]
y = transactions_df[output_feature]

X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=42, stratify=y
    )
# 评估模型AUC得分
print("### Evaluating model ###")
auc_score, feature_importance = evaluate_model(model, X_test, y_test,input_features)
print("### AUC得分:", auc_score)
y_pred = model.predict(X_test)
# 计算并打印精确率和召回率和F1得分
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
print(f"### 精确率: {precision:.4f}")
print(f"### 召回率: {recall:.4f}")
print(f"### F1得分: {f1:.4f}")